home *** CD-ROM | disk | FTP | other *** search
- Path: news.ox.ac.uk!news
- From: robert@robots.ox.ac.uk (Robert Smith)
- Newsgroups: comp.lang.c++
- Subject: Re: Virtuals in constructor
- Date: Thu, 22 Feb 1996 10:40:38 GMT
- Organization: Oxford University
- Message-ID: <4ghh6t$kbc@news.ox.ac.uk>
- References: <312A3A72.688D@scopus.ch>
- NNTP-Posting-Host: clitus.robots.ox.ac.uk
- X-Newsreader: Forte Free Agent v0.55
-
- Fabienne Guinnard <guinnard_f@scopus.ch> wrote:
-
- >Hi,
-
- >does anyone know why the following code doesn't work ?
-
- >Run-time error: pure virtual function called
-
- >class A
- >{
- > public:
- > A(VOID) { Method(); }
-
- > virtual VOID Method(VOID) = 0;
- >};
-
- >class B : public A
- >{
- > public:
- > B(VOID) {}
-
- > VOID Method(VOID) { MessageBox(NULL, "", "", MB_OK); }
- >};
-
- >int WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
- >{
- > B b;
-
- > return 0;
- >}
-
- >Thanks
-
- > Laurent Guinnard
- > guinnard@eig.unige.ch
-
- >be_well++;
-
- Here is an extract from an article on internals of C++:
-
- Constructors and Destructors
- As we have seen, sometimes there are hidden members that need to be
- initialized during construction and destruction. Worst case, a
- constructor may perform these activities
- ╖ If most-derived, initialize vbptr field(s) and call
- constructors of virtual bases.
- ╖ Call constructors of direct non-virtual base classes.
- ╖ Call constructors of data members.
- ╖ Initialize vfptr field(s).
- ╖ Perform user-specified initialization code in body of
- constructor definition.
-
- The problem is internally: the derived constructor (your B) invokes
- the base class constructor (your A) BEFORE it sets up the virtual
- function table for the derived class. Hence when the base class
- constructor executes, the virtual function table is setup for the base
- calss, and the base class Method is invoked.
-
- Only after the completed construction of the base classes is the
- virtual function table created, and the derived Method will be called.
-
- Rob Smith
- robert@robots.ox.ac.uk
-
-
-